using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using ShopForWeb.Model.Basic;

namespace ShopForWeb.UI.Utils.Extensions
{
  public static class ControllerExtensions
  {
    public static User? GetUser(this Controller controller)
    {
      var cookies = controller.HttpContext.Request.Cookies;
      string? jsonString;
      cookies.TryGetValue("key-user", out jsonString);
      if (string.IsNullOrEmpty(jsonString))
        return null;
      else
        return JsonConvert.DeserializeObject<User>(jsonString);
    }

    public static void SetUser(this Controller controller, User user)
    {
      var cookies = controller.HttpContext.Response.Cookies;
      var jsonString = JsonConvert.SerializeObject(user);
      cookies.Append("key-user", jsonString, new CookieOptions
      {
        Expires = DateTimeOffset.Now.AddDays(7) // 默认7天过期
      });
    }

    public static Admin? GetAdmin(this Controller controller)
    {
      var session = controller.HttpContext.Session;
      var jsonString = session.GetString("key-admin");
      if (string.IsNullOrEmpty(jsonString))
        return null;
      else
        return JsonConvert.DeserializeObject<Admin>(jsonString);
    }

    public static void SetAdmin(this Controller controller, Admin admin)
    {
      var session = controller.HttpContext.Session;
      var jsonString = JsonConvert.SerializeObject(admin);
      session.SetString("key-admin", jsonString);
    }
  }
}
